<template>
  <el-button :style="btnStyle" class="countdown-button" :type="type" :size="size" :disabled="loading" @click="toAction">
    <span v-if="btnCount===0">{{text}}</span>
    <span v-else>{{actionText||text}}({{btnCount}})</span>
  </el-button>
</template>

<script>
  export default {
    props: {
      width: String,
      text: String,
      actionText: String,
      beforeClickFun: Function,
      count: {
        type: Number,
        default: 5
      },
      type: String,
      size: String
    },

    computed: {
      btnStyle() {
        let style = {
          padding: '12px 0'
        };
        let width = this.width;
        if (width !== undefined) {
          style.width = width;
        }
        return style;
      }
    },

    data() {
      return {
        loading: false,
        timer: null,
        btnCount: 0
      };
    },

    beforeDestroy() {
      this.clearCountRun();
    },

    methods: {
      toAction() {
        let beforeClickFun = this.beforeClickFun;
        if (beforeClickFun === undefined) {
          this.loading = true;
          this.toRunTimer();
          return;
        }

        this.loading = true;
        beforeClickFun().then(flag => {
          if (flag) {
            this.toRunTimer();
          } else {
            this.loading = false;
          }
        }).catch(function () {
          this.loading = false;
        });
      },

      toRunTimer() {
        this.clearCountRun();

        this.btnCount = this.count;
        this.timer = setInterval(() => {
          let btnCount = this.btnCount;
          btnCount--;
          this.btnCount = btnCount;
          if (btnCount === 0) {
            this.clearCountRun();
            this.loading = false;
          }
        }, 1000);
      },

      clearCountRun() {
        let timer = this.timer;
        if (timer !== null) {
          clearInterval(timer);
        }
      },

      resetBtn() {
        this.clearCountRun();
        this.loading = false;
        this.btnCount = 0;
      }
    }
  };

</script>

<style lang="scss" scoped>

</style>
